package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.UserBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class TestServlet extends HttpServlet {
    public TestServlet(){
        System.out.println("servlet创建");
    }
    @Override
    public void init() throws ServletException {
        System.out.println("servlet初始化");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置MIME类型和编码集
        resp.setContentType("text/html;charset=utf-8");
        //向客户端输出文本数据
//        resp.getWriter().print("hello,中国");
//        OutputStream out = resp.getOutputStream();

        List<UserBean> list = new ArrayList<>();
        list.add(new UserBean(1,"张三", LocalDate.parse("2001-01-03"),10500,120.4));
        list.add(new UserBean(5,"李四", LocalDate.parse("1998-02-21"),6500,70.6));
        list.add(new UserBean(3,"王五", LocalDate.parse("2002-10-15"),8500,100.8));

        ObjectMapper om = new ObjectMapper();
        //注册时间模版
        om.registerModule(new JavaTimeModule());
        //将java对象转化为json字符串
        String str = om.writeValueAsString(list);
        resp.getWriter().print(str);
    }
}
